package com.tledu.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tledu.core.AjaxResult;
import com.tledu.model.Department;
import com.tledu.model.Product;
import com.tledu.service.DepartmentService;
import com.tledu.service.ProductService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RequestMapping("department")
@Controller
@AllArgsConstructor
public class DepartmentController {
    @Resource
    private DepartmentService departmentService;




    @RequestMapping("/list")
    public String pro(ModelMap modelMap,Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Department> departmentsList = departmentService.list();
        PageInfo<Department> pageInfo = PageInfo.of(departmentsList);
        modelMap.addAttribute("pageInfo",pageInfo);
        return "department/department-list";
    }


    @DeleteMapping("/delete")
    @ResponseBody
    public AjaxResult<Department> delete(String id){
        int i = departmentService.delete(id);
        if (i != 1){
            return new AjaxResult<Department>(false,"删除失败");
        }
        return new AjaxResult<Department>(true,"删除成功");
    }


    @PostMapping("/add")
    @ResponseBody
    public AjaxResult<Department> insert(Department department){
        int i = departmentService.insert(department);
        System.out.println(department);
        if (i != 1){
            return new AjaxResult<Department>(false,"添加失败");
        }
        return new AjaxResult<Department>(true,"添加成功");
    }

    @GetMapping("/add")
    public String toAddJsp(){
        return "department/department-add";
    }



    @GetMapping("/edit")
    public String toEditJsp(String id,ModelMap modelMap){
        Department department= departmentService.selectById(id);
        modelMap.addAttribute("department",department);
        return "department/department-edit";
    }



    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult<Department> update(@RequestBody  Department department){
        System.out.println(department);
        int i = departmentService.update(department);

        if (i != 1){
            return new AjaxResult<Department>(false,"修改失败,不能修改编号");
        }
        return new AjaxResult<Department>(true,"修改成功");
    }



}
